<template>
  <div class="login">
    <el-form
      class="login-form"
      :model="form"
      :rules="rules"
      ref="elform"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" @click="onSubmit" :loading="isLoginLoading"
          >登陆</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, getCurrentInstance } from 'vue'
import { login } from '/@/services/User'
import { ElForm, ElMessage } from 'element-plus'
import router from '/@/router/Index'
import store from '/@/store/Index'
import { useRoute } from 'vue-router'

export default defineComponent({
  name: 'LoginIndex',
  setup() {
    const route = useRoute()
    const form = ref({
      phone: '15510792995',
      password: '111111'
    })
    const isLoginLoading = ref(false)
    const rules = ref({
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
      ]
    })
    const elform = ref(null)
    const onSubmit = ref(async () => {
      try {
        // 1.表单验证
        await (elform.value as ElForm).validate()
        // 按钮loading
        isLoginLoading.value = true

        // 2.请求
        const { data } = await login(form.value)

        // 3.处理请求结果
        // 失败
        if (data.state !== 1) {
          // 结束按钮loading
          isLoginLoading.value = false
          ElMessage.error(data.message)
        }
        store.commit('setUser', data.content)
        // 成功
        router.push((route.query.redirect as string) || '/')
        ElMessage.success('登陆成功')
        // 结束按钮loading
        isLoginLoading.value = false
      } catch (error) {
        console.error(error)
      }
    })
    return {
      form,
      isLoginLoading,
      rules,
      onSubmit,
      elform
    }
  }
})
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  height: 100vh;
  justify-content: center;
  align-items: center;

  .login-form {
    width: 300px;
    padding: 20px;
    background: #fff;
    border-radius: 5px;

    .login-btn {
      width: 100%;
    }
  }
}
</style>
